package com.yyt.zookeeperdemo.service;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.WatchedEvent;

import java.util.List;

/**
 * @author yeyangtao
 * @since 2022/6/27 16:35
 */
public class CuratorDemo {
    /**
     * 重试等待的初始时间
     */
    private static final int BASE_SLEEP_TIME = 1000;
    /**
     * 重试最大次数
     */
    private static final int MAX_RETRIES = 3;


    public static void main(String[] args) throws Exception {
        // Retry strategy. Retry 3 times, and will increase the sleep time between retries.
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(BASE_SLEEP_TIME, MAX_RETRIES);
        CuratorFramework zkClient = CuratorFrameworkFactory.builder()
                // the server to connect to (can be a server list)
                .connectString("127.0.0.1:2181")
                .retryPolicy(retryPolicy)
                .build();
        zkClient.start();
        getChildren(zkClient, "/");
        //zkClient.delete().deletingChildrenIfNeeded().forPath("/yyt");
        getChildren(zkClient, "/");
        if (null == zkClient.checkExists().forPath("/yyt/yyt1")) {
            zkClient.create().creatingParentsIfNeeded().forPath("/yyt/yyt1", "111".getBytes());
        }
        getData(zkClient, "/yyt/yyt1");

        zkClient.getData().usingWatcher(new CuratorWatcher() {
            @Override
            public void process(WatchedEvent watchedEvent) throws Exception {
                System.out.println("watcher");
            }
        }).forPath("/yyt/yyt1");

        watchDemo(zkClient, "/yyt/yyt1");

        zkClient.setData().forPath("/yyt/yyt1", "222".getBytes());

        Thread.sleep(5000L);
    }

    private static void getData(CuratorFramework zkClient, String path) throws Exception {
        // 查数据
        byte[] res1 = zkClient.getData().forPath(path);
        System.out.println(new String(res1));
    }

    private static void getChildren(CuratorFramework zkClient, String path) throws Exception {
        // 查子节点
        List<String> res1 = zkClient.getChildren().forPath(path);
        System.out.println(res1);
    }

    private static void watchDemo(CuratorFramework zkClient, String path) throws Exception {
        PathChildrenCache pathChildrenCache = new PathChildrenCache(zkClient, path, true);
        PathChildrenCacheListener pathChildrenCacheListener = (curatorFramework, pathChildrenCacheEvent) -> {
            System.out.println("watch 监听到节点变化");
        };
        pathChildrenCache.getListenable().addListener(pathChildrenCacheListener);
        pathChildrenCache.start();
    }
}
